package com.example.menuvirtualclient.repository;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.example.menuvirtualclient.core.*;
import com.example.menuvirtualclient.data.Repository;

public class UserRepository extends Repository<User> {

	private static final String LOGTAG = "UserRepository";
	
	public UserRepository(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	public User GetByUser(String userName, String password){
		SQLiteDatabase db = null;
		User entity = null;
		String[] filter = new String[2];
		filter[0] = userName;
		filter[1] = password;
		try{
			if(!_session.IsOpen())
				_session.Open();
			
			db = _session.Connection();			
			Cursor cursor = db.rawQuery("SELECT id, firstname, lastname, username, password FROM Users WHERE username = ? AND password = ? ", filter);
			
			cursor.moveToFirst();
			entity = BuildNewEntity(cursor); 
			cursor.close();
		    db.close();
		}
		catch(Exception ex){
			Log.e(LOGTAG, ex.getMessage());			
		}
		finally{
			if(db != null)
				if(db.isOpen()) {
					db.close();
					Log.e(LOGTAG, "Close database");		
				}
		}
		return entity;
	}
	
	public User GetByUser(String password){
		SQLiteDatabase db = null;
		User entity = null;
		String[] filter = new String[1];
		filter[0] = password;
		try{
			if(!_session.IsOpen())
				_session.Open();
			
			db = _session.Connection();			
			Cursor cursor = db.rawQuery("SELECT id, firstname, lastname, username, password FROM Users WHERE password = ? ", filter);
			
			cursor.moveToFirst();
			entity = BuildNewEntity(cursor); 
			cursor.close();
		    db.close();
		}
		catch(Exception ex){
			Log.e(LOGTAG, ex.getMessage());			
		}
		finally{
			if(db != null)
				if(db.isOpen()) {
					db.close();
					Log.e(LOGTAG, "Close database");		
				}
		}
		return entity;
	}
	
	@Override
	public String getTableName() {
		return "Users";
	}
	
	@Override
	public User BuildNewEntity(Cursor cursor) {
		User user = new User();
		user.setId(cursor.getInt(0));
		user.setFirstName(cursor.getString(1));
		user.setLastName(cursor.getString(2));
		user.setUserName(cursor.getString(3));
		user.setPassword(cursor.getString(4));

		return user;
	}
}
